import win32api, win32gui, win32con, win32print, win32ui
from enum import Enum
import logging
import logging.config
from logging.handlers import RotatingFileHandler
import numpy as np
from PIL import ImageGrab, Image, ImageDraw, ImageFont

logging.config.fileConfig("./util/logging.conf")
logging.basicConfig(filename='yhbtestingameing.log', level=logging.DEBUG, force=True)
log = logging.getLogger("example")

"""
    在魔兽世界的界面中划出矩形，这个是直接在游戏界面中画，会被游戏帧数覆盖掉
    """
def drawRec(argw=0, argh=0, argtopleft=(0, 0), argColor=0, width=1):
    '''截图，输出Bitmapsbits的列表
    argw=0表示全宽，argh=0表示全高
    '''
    hwnd = 0  # 窗口的编号，0号表示当前活跃窗口
    hwndDC = win32gui.GetWindowDC(hwnd)  # 根据窗口句柄获取窗口的设备上下文DC（Divice Context）
    mfcDC = win32ui.CreateDCFromHandle(hwndDC)  # 根据窗口的DC获取mfcDC
    saveDC = mfcDC.CreateCompatibleDC()  # mfcDC创建可兼容的DC
    saveBitMap = win32ui.CreateBitmap()  # 创建bigmap准备保存图片
    MoniterDev = win32api.EnumDisplayMonitors(None, None)  # 获取监控器信息
    # 判断是否设置截图区域
    w = MoniterDev[0][2][2] if argw == 0 else argw
    h = MoniterDev[0][2][3] if argh == 0 else argh
    saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)  # 为bitmap开辟空间
    saveDC.SelectObject(saveBitMap)  # 高度saveDC，将截图保存到saveBitmap中
    # 截取从左上角（0，0）或者 tmptl 长宽为（w，h）的图片
    tx = 0 if argtopleft[0] <= 0 else argtopleft[0]
    ty = 0 if argtopleft[1] <= 0 else argtopleft[1]
    tmptl = (tx, ty)
    saveDC.BitBlt((0, 0), (w, h), mfcDC, tmptl, win32con.SRCCOPY)  # 目标矩形顶点(0,0)长宽(w,h),源设备mfcDC,源矩形顶点tmptl
    rtns = saveBitMap.GetBitmapBits()
    # # 绘制辅助框 暂时未解决透明问题
    hPen = win32gui.CreatePen(win32con.PS_SOLID, width, argColor)  # 定义框颜色
    win32gui.SelectObject(hwndDC, hPen)
    hbrush = win32gui.GetStockObject(win32con.NULL_BRUSH)  # 定义透明画刷，这个很重要！！
    prebrush = win32gui.SelectObject(hwndDC, hbrush)
    win32gui.Rectangle(hwndDC, tx - 1, ty - 1, tx + w + 2, ty + h + 2)  # 左上到右下的坐标
    win32gui.SelectObject(hwndDC, prebrush)
    # # 回收资源
    mfcDC.DeleteDC()
    saveDC.DeleteDC()
    win32gui.DeleteObject(hPen)
    win32gui.DeleteObject(hbrush)
    win32gui.DeleteObject(prebrush)
    win32gui.ReleaseDC(hwnd, hwndDC)
    return rtns

def drawText(sText):
    font = ImageFont.truetype("simsun.ttc", 40, encoding="unic")  # 设置字体
    # 画框，弹出截图，来定位截图位置是否正确
    hDC = win32gui.GetDC(0)
    w = win32print.GetDeviceCaps(hDC, win32con.DESKTOPHORZRES)  # 横向分辨率
    h = win32print.GetDeviceCaps(hDC, win32con.DESKTOPVERTRES)  # 纵向分辨率
    # 从配置文件中读取配置，确定左下角的wa的方块的位置是否正确,在弹出截图后，进行调整。
    imButton1 = ImageGrab.grab(
        bbox=(0, 0, w, h))  # X1,Y1,X2,Y2
    imButton1_numpy = np.array(imButton1.getdata(), dtype='uint8').reshape(
        (imButton1.size[1], imButton1.size[0], 3))
    imButton1_pil = Image.fromarray(imButton1_numpy)
    draw = ImageDraw.Draw(imButton1)

    draw.text((100 + 100, 700),
              sText, 'fuchsia',
              font)
    #imButton1.show()
    imButton1.save(r'e:/debug.jpg')
    return

def displayWeCanChat():
    # 画框，表示我们可以聊天了
    log.info('打印绿色框,标志我们可以开始聊天了')
    drawRec(50, 50, (50, 700), win32api.RGB(0, 255, 0),width=10)
    return

def doubleCheckPosByDrawRec(x,y,w,h,openWidth):
    # 检查某些取像素位置是否正确, openWidth笔的粗细
    drawRec(w, h, (x, y), win32api.RGB(0, 255, 0), width=openWidth)
    return

# 在opencv截图的图片中解决画矩形背景不透明的问题
def rectangleBy4Line(x1, y1, x2, y2, drawObj,width,color):
    # 画线
    drawObj.line([x1, y1, x2, y1, x2, y2, x1, y2, x1, y1], fill=color, width=width)
    # drawObj.line([x2, y1, x2, y2], fill=(0, 255, 0), width=5)
    # drawObj.line([x1, y2, x2, y2], fill=(0, 255, 0), width=5)
    # drawObj.line([x1, y1, x1, y2], fill=(0, 255, 0), width=5)

    return drawObj

class Lan(Enum):
    """
    语言代码值参考：https://msdn.microsoft.com/en-us/library/cc233982.aspx
    """
    EN = 0x4090409
    ZH = 0x8040804


def change_lan(lan: Lan):
    """
    修改当前激活窗口输入法
    :param lan: 语言类型
    :return: True 修改成功，False 修改失败
    """
    # 获取系统输入法列表
    hwnd = win32gui.GetForegroundWindow()
    im_list = win32api.GetKeyboardLayoutList()
    im_list = list(map(hex, im_list))

    # 加载输入法
    if hex(lan.value) not in im_list:
        win32api.LoadKeyboardLayout('0000' + hex(lan.value)[-4:], 1)

    result = win32api.SendMessage(
        hwnd,
        win32con.WM_INPUTLANGCHANGEREQUEST,
        0,
        lan.value)
    if result == 0:
        log.debug('设置%s键盘成功！' % lan.name)
    return result == 0